//
//  SleepViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/9/6.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "SleepViewController.h"
#import "SleepView.h"
#import "XTPopTableView.h"
#import "SleepSettingViewController.h"
#import "GetSleepRecordListApi.h"
#import "DTCalendarView.h"
#import "SleepChartViewController.h"

@interface SleepViewController ()<SelectIndexPathDelegate,DTCalendarDelegate>

@property(nonatomic,strong) SleepView *containerView;
@property(nonatomic,strong) UIButton *titleButton;
@property(nonatomic,assign) NSInteger dateIndex;

@end

@implementation SleepViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUI) name:BatteryState object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeCirCleAnimation) name:DeviceDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rotationCirCleAnimation) name:DeviceConnectSuccess object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getHistorySleep];

    DTCDeviceModel *model = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    if ([model.mac isEqualToString:EXRACT_OBJECT(MAC)])
    {
        [self rotationCirCleAnimation];
    }
    

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self refreshUI];
    [self getSleepInfo];
    self.dateIndex = 0;

}

- (void)refreshUI
{
    [self setRightButtonImage:[UIImage imageNamed:[NSString stringWithFormat:@"nav_icon_cell%@",[BlueToothDataHandle sharedInstance].battery]]];
    if (EXRACT_OBJECT(BraceletSleepTarget) || [EXRACT_OBJECT(BraceletSleepTarget) intValue] == 0)
    {
        self.containerView.targetView.dataLabel.text = [NSString stringWithFormat:@"%.1f",[EXRACT_OBJECT(BraceletSleepTarget) floatValue]/60];
        //[NSString stringWithFormat:@"%.1f",[EXRACT_OBJECT(BraceletSleepTarget) floatValue]/10];
    }
    else
    {
        self.containerView.targetView.dataLabel.text = @"8.30";
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)refreshBaseControlValue
{
    __weak typeof(self) weakSelf = self;
    [BlueToothDataHandle sharedInstance].sleepBlock = ^(NSString *deepSleep, NSString *lightSleep) {
        CGFloat deep = [deepSleep floatValue]/60;
        CGFloat light = [lightSleep floatValue]/60;
//        CGFloat deep = ceil([deepSleep floatValue]/60*10)/10;
//        CGFloat light = ceil([lightSleep floatValue]/60*10)/10;
        // 深睡眠和浅睡眠不需要四舍五入，总睡眠四舍五入
        CGFloat count = ceil((deep + light)*10)/10;
        weakSelf.containerView.stepLabel.text = [NSString stringWithFormat:@"%.1f",count];
        weakSelf.containerView.dateView.dataLabel.text = [NSString stringWithFormat:@"%.1f",deep];
        weakSelf.containerView.distanceView.dataLabel.text = [NSString stringWithFormat:@"%.1f",light];
        weakSelf.containerView.titleLabel.text = MyNSLocalizedString(@"今日睡眠");
        //;
    };
}

- (void)updateSportWithTitle:(NSString *)title sleep:(NSString *)sleep deepSleep:(NSString *)deepSleep lightSleep:(NSString *)lightSleep
{
    self.containerView.titleLabel.text = title;
    self.containerView.stepLabel.text = sleep;
//    self.containerView.tipLabel.text = [NSString stringWithFormat:@"%@%@%@",MyNSLocalizedString(@"消耗"),[NSString stringWithFormat:@"%.3f",[calorie floatValue]/1000],MyNSLocalizedString(@"千卡")];
    self.containerView.dateView.dataLabel.text = deepSleep;
    self.containerView.distanceView.dataLabel.text = lightSleep;
}

#pragma mark - 点击事件
- (void)didClickTitleButton:(id)sender
{
    self.titleButton.selected = !self.titleButton.selected;
    [XTPopTableView showPopViewByCenter:sender valueList:@[MyNSLocalizedString(@"统计"),MyNSLocalizedString(@"设置"),MyNSLocalizedString(@"分享")] imageList:@[@"icon_statis",@"icon_set",@"icon_share"] delegate:self];
}

- (void)didClickDateButton
{
    [DTCalendarView showCalendarViewByDelegate:self];
}

- (void)didClickLeftButton
{
    [self getDateWithIndex:-1];
}

- (void)didClickRightButton
{
    [self getDateWithIndex:1];
    
}

#pragma mark - 事件处理
- (void)getSleepRecordListWithDate:(NSString *)date
{
    GetSleepRecordListApi *api = [[GetSleepRecordListApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"sdate":date,@"edate":date}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *data = [request responseJSONObject];
        if ([data[@"errcode"] intValue] == 0)
        {
            NSString *title = [NSString stringWithFormat:@"%@.%@%@",date.subString(4,6),date.subString(6,8),MyNSLocalizedString(@"睡眠")];
            
            if ([data[@"data"] count] > 0)
            {
                NSDictionary *dict = [data[@"data"] firstObject];
                [self updateSportWithTitle:title sleep:[NSString stringWithFormat:@"%.1f",([dict[@"deep_sleep"] floatValue] + [dict[@"light_sleep"] floatValue])/10] deepSleep:[NSString stringWithFormat:@"%.1f",[dict[@"deep_sleep"] floatValue]/10] lightSleep:[NSString stringWithFormat:@"%.1f",[dict[@"light_sleep"] floatValue]]];
                NSLog(@"%@",dict);
            }
            else
            {
//                [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"当天没数据")];
                [self updateSportWithTitle:title sleep:@"0" deepSleep:@"0" lightSleep:@"0"];
            }
            
        }
        
    } failure:nil];
}

- (void)getSleepInfo
{
    DTCDeviceModel *device = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    NSData *sendData = [NSString convertHexStrToData:getLastSleepCode];
    [[DTCBlueToothSendData sharedInstance] sendDataByData:sendData andInfo:device];
}

- (void)getHistorySleep
{
    DTCDeviceModel *device = [DTCBluetoothManager shareInstance].connectedDeviceList.lastObject;
    NSData *sendData = [NSString convertHexStrToData:getSleepHistoryCode];
    [[DTCBlueToothSendData sharedInstance] sendDataByData:sendData andInfo:device];
    
}

- (void)getDateWithIndex:(NSInteger)index
{
    self.dateIndex += index;
    if (self.dateIndex < 0)
    {
        NSTimeInterval secondsPerDay = 24 * 60 * 60 * self.dateIndex;
        NSDate *today = [[NSDate alloc] init];
        NSDate *yesterday = [today dateByAddingTimeInterval: secondsPerDay];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYYMMdd";
        NSLog(@"%@", [formatter stringFromDate:yesterday]);
        [self getSleepRecordListWithDate:[formatter stringFromDate:yesterday]];
    }
    else
    {
        self.dateIndex = 0;
        [self getSleepInfo];
    }
    
}

- (void)removeCirCleAnimation
{
    [self.containerView.circleView.layer removeAllAnimations];
}

- (void)rotationCirCleAnimation
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 2;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1000;
    [self.containerView.circleView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

#pragma mark - 代理
- (void)selectIndexPathRow:(NSInteger )index
{
    switch (index) {
        case 0:
        {
            SleepChartViewController *vc = [[SleepChartViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            SleepSettingViewController *vc = [[SleepSettingViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {
            UIImage *screenShot = [OTScreenshotHelper screenshot];
            [ShareView showShareViewWithClickShareBlock:^(ShareType shareType) {
                [DTCSharePlatformManager shareWithImage:screenShot Type:shareType];
            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)closePopView
{
    self.titleButton.selected = !self.titleButton.selected;
}

- (void)selectDate:(NSDate *)date
{
    NSDate *nowDate = [NSDate date];
    NSInteger nowSp = [[NSNumber numberWithDouble:[nowDate timeIntervalSince1970]] integerValue];
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    NSLog(@"当前时间：%li 之前时间：%li",(long)nowSp,(long)timeSp);
    if (timeSp + 24*60*60 < nowSp)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYYMMdd";
        NSLog(@"%@", [formatter stringFromDate:date]);
        [self getSleepRecordListWithDate:[formatter stringFromDate:date]];
        self.dateIndex = -(nowSp - timeSp)/24/60/60;

    }
    else
    {
        self.containerView.stepLabel.text = @"0";
        self.containerView.dateView.dataLabel.text = @"0";
        self.containerView.distanceView.dataLabel.text = @"0";
        self.containerView.titleLabel.text = MyNSLocalizedString(@"今日睡眠");
        [self getSleepInfo];
    }

}

#pragma mark - 通知处理

#pragma mark - 初始化
- (SleepView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[SleepView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.dateButton addTarget:self action:@selector(didClickDateButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.leftButton addTarget:self action:@selector(didClickLeftButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.rightButton addTarget:self action:@selector(didClickRightButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}

- (UIButton *)titleButton
{
    if(!_titleButton)
    {
        UIView *superView = self.view;
        _titleButton = [[UIButton alloc]init];
        [superView addSubview:_titleButton];
        [_titleButton setTitle:MyNSLocalizedString(@"睡眠") forState:UIControlStateNormal];
        [_titleButton setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
        [_titleButton setImage:[UIImage imageNamed:@"up"] forState:UIControlStateSelected];
        [_titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_titleButton sizeToFit];
        [_titleButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:4];
        [_titleButton addTarget:self action:@selector(didClickTitleButton:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _titleButton;
}

- (void)setNavigationStyle
{
    [self setTitleView:self.titleButton];

    [self setRightButtonImage:[UIImage imageNamed:@"nav_icon_cell1"]];
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.equalTo(superView);
    }];
    
}

@end
